<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {
	public function __construct()
    {
        parent::__construct();
		$this->load->library('session');
		$this->load->helper(array('form', 'url'));
		if($this->session->userdata('logged_in')){
			if($this->session->userdata('user_type')==0){
				redirect('admin');
			}else{
				redirect('client');
			}
		}
    } 
	public function index()
	{
		$this->load->library('form_validation');
		$this->load->model('Usermodel');
		$data['adminInfor'] = $this->Usermodel->getAdminInfo();
		
		$this->form_validation->set_rules('username', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('login', $data);
		}
		else
		{
			$userName=$this->input->post('username');
			$password=$this->input->post('password');
			$userInfor = $this->Usermodel->validateUser($userName, $password);
			if($userInfor == null){
				$data['loginError'] = "Invalid Username or password";
				$this->load->view('login', $data);
				
			}else{
				$newdata = array(
					'userid' => $userInfor->id,
                   'username'  => $userInfor->username,
				   'user_type' => $userInfor->user_type,
				   'is_wife'   => $userInfor->is_wife,
                   'logged_in' => TRUE
				);
				$this->session->set_userdata($newdata);
				if($userInfor->user_type==0){
					redirect('admin');
				}else{
					redirect('client');
				}
			}
		}	
	}
}